package com.example.dense_rack_server.utils.Netty;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.Host;
import com.example.dense_rack_server.mapper.HostMapper;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * 发送命令封装工具类
 */
@Slf4j
@Component
public class SendCmd {

    /**
     * 密集架对接协议添加包头长度
     * @param str
     * @return
     */
    public static byte[] parse(String str) {
//        byte[] body = str.getBytes(Charset.defaultCharset());
        byte[] body = str.getBytes(StandardCharsets.UTF_8);
        ByteBuffer bb = ByteBuffer.allocate(4 + body.length);
//        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(body.length);
        bb.put(body);
        return bb.array();
    }

    @Resource
    public HostMapper hostMapper;

    public void send(String cmdName, HttpServletRequest request, String appointIp) {
        String sendIpAddress = "";
        if (request != null) {
            HttpSession session = request.getSession();
            sendIpAddress = Convert.toStr(session.getAttribute("cabinet"));
        } else {
            sendIpAddress = appointIp;
        }
        Iterator<Channel> iterator = NettyServerHandler.channelGroup.iterator();
        while (iterator.hasNext()) {
            Channel channel = iterator.next();
//        NettyServerHandler.channelGroup.forEach(channel -> {
            if (sendIpAddress.equals(channel.remoteAddress().toString().split(":")[0].replace("/", ""))) {
                Host host = hostMapper.selectOne(new QueryWrapper<Host>().eq("ip", sendIpAddress));
                if (host != null) {

                        // 密集架
                        try {
                            String nowTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss:SSS");
                            System.out.println("时间:" + nowTime + "已发送  " + "主机ip是  " + sendIpAddress + "命令为 " + cmdName + "\r\n");
                            byte[] TemplatesToSendData = parse(cmdName);
                            channel.writeAndFlush(Unpooled.buffer().writeBytes(TemplatesToSendData));
                        } catch (Exception e) {
                            log.error("密集架命令发送失败", e);
                        }
                        break; // 找到匹配的Channel后停止循环
                }
            } else {
                System.out.println("未发送");
            }
        }
    }
}
